package com.aqgj.Role.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.Role.bean.Role;
import com.aqgj.Role.dao.RoleDao;
import com.aqgj.RoleResource.bean.RoleResource;
import com.aqgj.RoleResource.dao.RoleResourceDao;
import com.aqgj.UserRole.bean.UserRole;
import com.aqgj.UserRole.dao.UserRoleDao;
import com.aqgj.util.Pager;
import com.aqgj.util.Tree;
import com.ztc.util.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service("Role")
public class RoleManager {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleResourceDao roleResourceDao;

    public List<Role> selectAll() {
        return roleDao.getAll();
    }

    public Pager<Role> selectDataGrid(Integer pageSize, Integer pageNumber) {
        return roleDao.getRoles(pageSize,pageNumber);
    }

    public void updateRoleResource(String roleId, JSONArray resourceIds) {
        // 先删除后添加,有点爆力
        List<RoleResource> roleResourceList = roleResourceDao.findBy("roleId",roleId);
        for(RoleResource roleResource:roleResourceList){
            roleResourceDao.remove(roleResource);
        }
        for (Iterator iterator = resourceIds.iterator(); iterator.hasNext();) {
            JSONObject jsonObject = (JSONObject)iterator.next();
            int checked = 0;
            if ("true".equals(jsonObject.getString("checked"))){
                checked = 1;
            }
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(roleId);
            roleResource.setChecked(checked);
            roleResource.setResourceId(jsonObject.getString("id"));
            roleResourceDao.save(roleResource);
        }
    }

    public void insertRole(Role role){
        roleDao.save(role);
    }

    public void deleteById(String id){
        List<UserRole> userRoleList = userRoleDao.findBy("roleId",id);
        if(userRoleList.size()>0){
            throw new BusinessException("删除失败，该角色已被用户使用！");
        }
        List<RoleResource> roleResourceList = roleResourceDao.findBy("roleId",id);
        for(RoleResource roleResource:roleResourceList){
            roleResourceDao.remove(roleResource);
        }
        roleDao.removeById(id);
    }

    public Role selectRoleById(String id){
        return roleDao.get(id);
    }

}
